/**
 *    TimedProfiles - let Android perform tasks based on conditions
 *    Copyright (C) 2011  Daniel Weinhold
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * */
package de.drak.Profiles;

//List View

import android.graphics.drawable.Drawable;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
//search activities
import java.util.List;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;

//other
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;

/**
 * This Class allows the user to pick a third party App.
 * Displayed Apps are filtered by an Intent they must accept.
 * The Class can also return a second Class of the picked App that takes another Intent.
 * 
 * Call this Class with a Bundle:
 * 	BUNDLE_INTENT:			Intent used for filtering
 * 	BUNDLE_SECOND_INTENT:	Intent for other Class or null
 * */
public class ActivityPicker extends Activity {
	public static final int MENU_CANCEL = Menu.FIRST;
	public static final String BUNDLE_INTENT = "searchFor";
	public static final String BUNDLE_SECOND_INTENT = "getClass";
	
	private AlertDialog mDialog;
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      
      //GetData
      mDialog = null;
      packets = null;

      toLoad = getIntent().getStringExtra(BUNDLE_INTENT);
      if(toLoad==null)
      {
    	  toLoad = Intent.ACTION_MAIN;
      }
      fetchExtra = getIntent().getStringExtra(BUNDLE_SECOND_INTENT);

      pm = getPackageManager();

      //Layout - everything is done in a Dialog
      requestWindowFeature(Window.FEATURE_NO_TITLE);
      
      ListView l2 = new ListView(this);
      
  	final AlertDialog.Builder builder = new AlertDialog.Builder(this);
	mDialog = builder.setCancelable(true).setOnCancelListener(new DialogInterface.OnCancelListener() {
		public void onCancel(DialogInterface dialog) {
			finish();
		}
	}).setView(l2).setTitle(R.string.task_add).create();//.setInverseBackgroundForced(true)
      
	l2.setOnItemClickListener(ListButtons);

		
    	packets = pm.queryIntentActivities(new Intent(toLoad), 0);
       int x = packets.size();
       
       CharSequence[] db_name = new CharSequence[x];
       long[] db_id = new long[x];
       Drawable[] db_icon = new Drawable[x];
       
	    for(;0<x;--x)
	    {
    		db_name[x-1] = packets.get(x-1).loadLabel(pm);
    		db_id[x-1] = x-1;
    		db_icon[x-1] = packets.get(x-1).loadIcon(pm);
	    }
	    
    	  l2.setAdapter(new ListAdapter(this, db_id, db_name, null, db_icon));
    	
	}
	@Override
	public void onResume()
	{
		super.onResume();
		if(mDialog!=null)
			mDialog.show();
	}
	@Override
	public void onPause()
	{
		super.onPause();
		if(mDialog!=null)
			mDialog.dismiss();
	}
  private OnItemClickListener ListButtons = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

			if(id==-1)
			{
				//header
				return;
			}
    	  ResolveInfo activity = packets.get((int) id/*Integer.parseInt((String)v.getTag())*/);


    	  Intent result = new Intent();
    	  result.putExtra("ActivityName", activity.activityInfo.name);
    	  result.putExtra("ActivityPackage", activity.activityInfo.packageName);
    	  
    	  //get extra -> fetch a fitting receiver to
    	  if(fetchExtra!=null)
    	  {
    		  List<ResolveInfo> extra_packs = pm.queryBroadcastReceivers(new Intent(fetchExtra), 0);
    		  int x = extra_packs.size()-1;          
   	    	for(;0<=x;--x)
   	    	{
   	    		if(extra_packs.get(x).activityInfo.packageName.compareTo(activity.activityInfo.packageName)==0){
   	    			result.putExtra("ActivityReceiver", extra_packs.get(x).activityInfo.name);
   	    			break;
   	    		}
   	    	}
    	  }
    	  
          setResult(RESULT_OK, result);
          finish();
      }
  };
  
  
  private List<ResolveInfo> packets;
  private String toLoad;
  private String fetchExtra;
  private PackageManager pm;


	@Override
	public boolean onCreateOptionsMenu(final Menu menu)
	{
		super.onCreateOptionsMenu(menu);

		//Help
		final Intent helpIntent = new Intent(this, OnlineHelp.class);//("com.twofortyfouram.Intent.ACTION_HELP");
		helpIntent.putExtra(OnlineHelp.HELP_URL, OnlineHelp.HELP_URL_PRE+"pick_plugin");
		helpIntent.putExtra(TimedProfiles.INTENT_TITLE, getTitle().toString());



		menu.add(R.string.onlinehelp)
			.setIcon(android.R.drawable.ic_menu_help).setIntent(helpIntent);
		
		menu.add(0, MENU_CANCEL, 0, android.R.string.cancel)
		.setIcon(android.R.drawable.ic_menu_close_clear_cancel).getItemId();
		

		return true;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean onMenuItemSelected(final int featureId, final MenuItem item)
	{
		switch (item.getItemId())
		{
			case MENU_CANCEL:
			{
				setResult(RESULT_CANCELED);
				finish();
				return true;
			}
		}

		return super.onOptionsItemSelected(item);
	}
  
  
}
